//
//  JOAuthVC.swift
//  JMicroBlog
//
//  Created by Jason on 19/5/15.
//  Copyright (c) 2015 Shepherd. All rights reserved.
//
/**
 *   OAuth的授权流程的网址请求
 *   涉及到的相关页面
     1.加载登录页面
     "https://api.weibo.com/oauth2/authorize?client_id=978327776&redirect_uri=http://itheima.com"

     2.单击登录按钮
     "https://api.weibo.com/oauth2/authorize"
      新浪返回的code
     "http://itheima.com/?code=ad0746a9c03953d8a0add36d58ea816f"

     根据code去
     https://api.weibo.com/oauth2/access_token 请求获得accesstoken

     某次次返回accesstoken如下
     {
       "access_token" = "2.00BBaotFQkxMEBd10e26c5d5s6UBWC";
       "expires_in" = 115951;
       "remind_in" = 115951;
       uid = 5405417487;
     }

    根据accesstoken访问受限的资源,在这里就微博用户的信息
    https://api.weibo.com/2/users/show.json

 */
import UIKit
import SVProgressHUD

// MARK: - 授权控制器类
class JOAuthVC: UIViewController {
    
    // MARK: - 属性
    private var webView : UIWebView {
        return view as! UIWebView
    }
    
    private let WB_Client_Id = "978327776" //"2680875383"   // 第三方应用Id
    
    private let WB_Redirect_Uri = "http://www.itheima.com"  // 第三方应用的回调地址
    // 第三方应用的Secrect
//    private let WB_Client_Secret = "6ce8f9f78b3e0477e7c1dad7aa3e1126" //
    private let WB_Client_Secret = "98ed3fe543395ac385621d4c810db467"
    
    // 第三方应用access_token请求页面
    private let WB_Access_Token_URL = "https://api.weibo.com/oauth2/access_token"
    
    // MARK: - 关键方法
    // 在该方法调用在视图出现才会进行加载请求 UE比较好
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        loadOAuthPage()  // 加载OAuth认证视图
    }
    
    // 关闭OAuth认证页
    @IBAction func closeOAuth() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 加载认证页面
    private func loadOAuthPage() {
        // 请求URL
        let url = NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_Id)&redirect_uri=\(WB_Redirect_Uri)")
        
        // 使用request加载请求页面
        webView.loadRequest(NSURLRequest(URL: url!))
    }
    
    // 请求获得AccessToken
    private func loadAccessToken(code:String) {
        let params = [
            "client_id":WB_Client_Id,
            "client_secret":WB_Client_Secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_Redirect_Uri
        ]
        JAccount.loadAccessToken(params){ (user, error) in
            if user != nil {
                sharedUserInfo = user
                JLog.i("-->账户信息:\(user)",false)
                // 发送通知到欢迎界面
                NSNotificationCenter.defaultCenter().postNotificationName(JExchangeRootVCNotification, object: "JWelcome")
                
                // 如果注释了 modal出来的视图控制器不会被释放,有内存泄露(下次不走该流程,自然不会有这个问题,但是还是需要注意)
                self.dismissViewControllerAnimated(true, completion: nil)
                
                return
            }
            
            SVProgressHUD.showInfoWithStatus("亲,您的网络不给力")
            JLog.i(error,false)
        }
    }
}

extension JOAuthVC : UIWebViewDelegate {
    
    /**
    返回true,正常工作流程不会被打断
    
    :param: webView        具体的UIWebView
    :param: request        请求
    :param: navigationType <#navigationType description#>
    
    :returns: <#return value description#>
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString!
        
        // 1.http://api.weibo.com 开头的继续加载
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        
        // 2. 不是回调地址开头的全部取消加载
        if !urlString.hasPrefix(WB_Redirect_Uri) {
            return false
        }
        
        // 
        let codeStr = "code="
        let query = request.URL!.query! // 请求字符串
        // 包含"code="
        if query.hasPrefix(codeStr) {
            // 获得请求码
            let code = (query as NSString).substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
            loadAccessToken(code)
        } else {
            JLog.i("用户拒绝授权",false)
            closeOAuth()
        }
        
        return false
    }
    
    /**
    开始加载页面
    
    :param: webView 加载的网页视图的webView
    */
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    /**
    页面加载完成后
    
    :param: webView 加载网页视图的webView
    */
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /**
    页面加载失败
    
    :param: webView 加载网页视图的webView
    :param: error   错误信息对象
    */
    func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
        // SVProgressHUD.showErrorWithStatus("亲:您的网络不给力")
        JLog.i(error,false)
    }
}
